<template>
  <div>
    <div class="header-bar" :class="bourse">
      <div class="layout-logo"></div>
      <Menu class="header-enu" mode="horizontal" theme="dark" :active-name="activeName" @on-select="selectMenu">
        <div >
          <admin_header v-if="viewAccessSuper"></admin_header>
          <normal_header  v-if="viewAccessAll"></normal_header>
        </div>
      </Menu>
      <div class="select-time">
        <DatePicker type="datetime" placeholder="开始时间" style="width: 200px" v-model="strategy_time.start_time" @on-change="change_startTime"></DatePicker>
        <DatePicker type="datetime" placeholder="结束时间" style="width: 200px" v-model="strategy_time.end_time" @on-change="change_endTime"></DatePicker>
        <Button  type="primary" @click="startback">开始回测</Button>
        <Button  type="primary" @click="stopback">暂停回测</Button>
        <Button  type="primary" @click="stopBackTest">终止回测</Button>
        <Button  type="primary" @click="resetData">复位</Button>
        <Button  type="primary" @click="deleteback">删除策略</Button>
      </div>
      <div class="custom-content-con">
        <Dropdown  @on-click="changeMenu">
          <Avatar src="..\..\..\static\img\account-normal.png" size="65" />
          <span href="javascript:void(0)" class="black" style="color: #FFFFFF">
                  {{user}}
                  <Icon type="ios-arrow-down"></Icon>
                </span>
          <DropdownMenu slot="list">
            <DropdownItem  name="theme"><a href="javascript:void(0)" style="width: 100%" >切换主题</a></DropdownItem>
            <DropdownItem  name="update"><a href="javascript:void(0)" style="width: 100%" >修改密码</a></DropdownItem>
            <DropdownItem  name="tuichu"><a href="javascript:void(0)" style="width: 100%" >退出登录</a></DropdownItem>
          </DropdownMenu>
        </Dropdown>
      </div>
      <Modal
        v-model="client_modall"
        :title="client_modall_title"
        :ok-text = "client_modall_ok"
        @on-ok ="client_update"
        :mask-closable = false
        :loading ='true'
        width="400">
        <div>
          <Form>
            <FormItem label="用户名" :label-width="150" style="margin-bottom: 10px;">
              <Input v-model="update_client_data.trader" disabled="disabled"></Input>
            </FormItem>
            <FormItem label="	密码" :label-width="150" style="margin-bottom: 10px;">
              <Input v-model="update_client_data.password" ></Input>
            </FormItem>
            <FormItem label="输入谷歌验证码" :label-width="150" style="margin-bottom: 10px;">
              <Input v-model="update_client_data.googlekey" ></Input>
            </FormItem>
          </Form>
        </div>
      </Modal>
    </div>
    <slot></slot>
  </div>
</template>

<script>
  import {
    updateTraderPassword,
  } from '@/api/trader'
  import {
    startBack,
    deleteBack,
    stopBack,
    resetData,
    setTime,
    getDefultTime,
    stopBackTest
  } from '@/api/trade'
  import { hasOneOf,TimeToDate } from '@/libs/tools'
  import { mapGetters,mapMutations,mapActions } from 'vuex'
  import admin_header from './admin_header'
  import normal_header from './normal_header'
  import { removeWatermark, setWaterMark } from '@/common/watermark'
    export default {
      components:{
        admin_header,
        normal_header
      },
      name: "base-com",
      data(){
        return{
          user:this.$store.getters.getUser,
          activeName:this.$router.path, //高亮
          client_modall:false,
          client_modall_title:'修改密码',
          client_modall_ok:'修改',
          update_client_data:{
            trader:'',
            password:'',
            googlekey:'',
          },
          select_datetime:'',
          strategy_time:{
            start_time:'',
            end_time:'',
          },
          clientSelected:'',
          contractSelected:'',
          startTime:'',
          endTime:'',
          bourse:'huobi',
        }
      },
      methods:{
        ...mapActions([
          'handleLogOut',
          'getListStrategypro',
        ]),
        ...mapGetters([
          'get_client',
          'get_contract',
          'get_start_time',
          'get_end_time',
        ]),
        ...mapMutations([
          'set_list_strategy',
          'set_list_strategy_unrun',
          'set_list_strategy_run',
          'set_data_group_id_run',
          'set_data_group_id_unrun',
          'set_all_group',
          'set_run_group',
          'set_unrun_group',
          'set_start_time',
          'set_end_time',
        ]),
        changeMenu(name){
          // this.reload();
          if(name === 'tuichu' ){
            this.handleLogOut().then(() => {
              this.$router.push({
                name: 'login'
              })
            });
            console.log('退出成功！');
          }else if(name === 'update'){
            this.update_client_data.trader = this.user;
            this.client_modall = true;
          }else if(name === 'theme'){
            this.changeColor();
          }
        },
        //更换主题
        changeColor(){
          if(localStorage.getItem("themeValue") === 'dark'){
            localStorage.setItem("themeValue",'light');
            document.getElementById('app').className = localStorage.getItem("themeValue");
            if(document.getElementsByClassName('trade_main_modal')[0] !== undefined){
              document.getElementsByClassName('trade_main_modal')[0].className = "trade_main_modal v-transfer-dom " +localStorage.getItem("themeValue");
            }
          }else if(localStorage.getItem("themeValue") === 'light'){
            localStorage.setItem("themeValue",'dark');
            document.getElementById('app').className = localStorage.getItem("themeValue");
            if(document.getElementsByClassName('trade_main_modal')[0] !== undefined){
              document.getElementsByClassName('trade_main_modal')[0].className = "trade_main_modal v-transfer-dom " +localStorage.getItem("themeValue");
            }
          }else {
            localStorage.setItem("themeValue","dark");
            document.getElementById('app').className = localStorage.getItem("themeValue");
            if(document.getElementsByClassName('trade_main_modal')[0] !== undefined){
              document.getElementsByClassName('trade_main_modal')[0].className = "trade_main_modal v-transfer-dom " +localStorage.getItem("themeValue");
            }
          }
        },
        selectMenu(name){
          this.$router.push({
            path:'/'+name})
        },
        client_update(){
          let params ={
            trader:this.update_client_data.trader,
            password:this.update_client_data.password,
            googlekey:this.update_client_data.googlekey,
          };
          updateTraderPassword(params).then(res=>{
            this.client_modall = false;
            if(res.data.code === 1000){
              this.$Message.success('修改成功');
            }else{
              this.$Message.error(res.data.data);
            }
            this.update_client_data = {
              trader:'',
              password:'',
              googlekey:'',
            }
          })
            .catch((e) =>{
              this.$Message.error("修改失败");
              this.update_client_data = {
                trader:'',
                password:'',
                googlekey:'',
              }
            })
        },
        menuList(){  // 这个方法里定义好，高亮和路由
          let path = this.$route.name;
          this.activeName=path
        },
        startback(){
          console.log(this.strategy_time.start_time)
          let params ={
            user_name:this.clientSelected,
            contract_type:this.contractSelected,
            start_time:this.strategy_time.start_time ===''? this.getDate() : this.strategy_time.start_time.getTime() ,
            end_time:this.strategy_time.end_time ===''? this.getDate(1) : this.strategy_time.end_time.getTime(),
          };
          startBack(params).then(res=>{
            if(res.data.code === 1000){
              this.$Message.success(res.data.msg);
              this.get_ListStrategy2()
            }else{
              this.$Message.error(res.data.msg);
            }
          })
            .catch((e) =>{
              this.$Message.error("业务异常");
            })
        },
        stopback(){
          let params ={
            user_name:this.clientSelected,
            contract_type:this.contractSelected,
          };
          stopBack(params).then(res=>{
            console.log(res.data)
            if(res.data.code === 1000){
              this.$Message.success(res.data.msg);
              this.get_ListStrategy2()
            }else{
              this.$Message.error(res.data.msg);
            }
          })
            .catch((e) =>{
              this.$Message.error("业务异常");
            })
        },
        stopBackTest(){
          let params ={
            user_name:this.clientSelected,
            contract_type:this.contractSelected,
          };
          stopBackTest(params).then(res=>{
            console.log(res.data)
            if(res.data.code === 1000){
              this.$Message.success(res.data.msg);
              this.get_ListStrategy2()
            }else{
              this.$Message.error(res.data.msg);
            }
          })
            .catch((e) =>{
              this.$Message.error("业务异常");
            })
        },
        resetData(){
          let params ={
            user_name:this.clientSelected,
            contract_type:this.contractSelected,
          };
          resetData(params).then(res=>{
            console.log(res.data)
            if(res.data.code === 1000){
              this.$Message.success(res.data.msg);
              this.get_ListStrategy2()
            }else{
              this.$Message.error(res.data.msg);
            }
          })
            .catch((e) =>{
              this.$Message.error("业务异常");
            })
        },

        deleteback(){
          let params ={
            user_name:this.clientSelected,
            contract_type:this.contractSelected,
          };
          deleteBack(params).then(res=>{
            if(res.data.code === 1000){
              this.$Message.success(res.data.msg);
              this.set_list_strategy([]);
              this.set_list_strategy_run([]);
              this.set_list_strategy_unrun([]);
              this.set_data_group_id_run([]);
              this.set_data_group_id_unrun([]);
              this.set_all_group([]);
              this.set_run_group([]);
              this.set_unrun_group([]);
            }else{
              this.$Message.error(res.data.msg);
            }
          })
            .catch((e) =>{
              console.log(e)
              this.$Message.error("删除失败");
            })
        },

        getDate(dates) {
          var dd = new Date();
          var n = dates || 0;
          dd.setDate(dd.getDate() + n);
          var y = dd.getFullYear();
          var m = dd.getMonth() + 1;
          var d = dd.getDate();
          m = m < 10 ? "0" + m: m;
          d = d < 10 ? "0" + d: d;
          var day = y + "-" + m + "-" + d;
          return new Date(day).getTime()-8*60*60*1000;
        },

        get_ListStrategy2(){
          let client = this.clientSelected; //用户ID（用户名）
          let contract = this.contractSelected;//合约名称
          this.getListStrategypro({client,contract}).then(res =>{
            console.log(res);
          }).catch(err =>{
            console.log(err)
          })
        },
        change_startTime(val){
          this.startTime = val ===''? "" : new Date(val).getTime();
          console.log(this.startTime)
          this.set_Time()
          this.set_start_time(this.startTime)
        },
        change_endTime(val){
          this.endTime = val ===''? "" : new Date(val).getTime();
          console.log(this.endTime)
          this.set_Time()
          this.set_end_time(this.endTime)
        },
        set_Time(){
          let params ={
            user_name:this.clientSelected,
            contract_type:this.contractSelected,
            start_time:this.startTime,
            end_time:this.endTime,
          };
          setTime(params).then(res =>{
            console.log(res);
          }).catch(err =>{
            console.log(err)
          })
        },
        get_DefultTime(){
          let params ={
            user_name:this.clientSelected,
            contract_type:this.contractSelected,
          };
          getDefultTime(params).then(res =>{
            console.log(res)
            if(res.data.code === 1000){
              if(res.data.data.start_time !==""){
                // this.strategy_time.start_time = TimeToDate(res.data.data.start_time, 'year')
                this.strategy_time.start_time = new Date(parseInt(res.data.data.start_time))
                this.startTime = res.data.data.start_time
              }
              if(res.data.data.end_time !==""){
                // this.strategy_time.end_time = TimeToDate(res.data.data.end_time, 'year')
                this.strategy_time.end_time = new Date(parseInt(res.data.data.end_time))
                this.endTime = res.data.data.end_time
              }
            }else {
              this.strategy_time.start_time = ""
              this.strategy_time.end_time = ""
              this.startTime = ""
              this.endTime = ""
            }
          }).catch(err =>{
            console.log(err)
          })
        }
      },
      created() {
        this.clientSelected = this.get_client();
        this.contractSelected = this.get_contract();
        this.strategy_time.start_time = this.get_start_time() !== "" ? TimeToDate(this.get_start_time(), 'year') : "";
        this.strategy_time.end_time = this.get_end_time() !== "" ? TimeToDate(this.get_end_time(), 'year') : "";
      },
      mounted() {
        this.menuList();
        //主题
        if(localStorage.getItem("themeValue")){
          document.getElementById('app').className = localStorage.getItem("themeValue");
          if(document.getElementsByClassName('trade_main_modal')[0] !== undefined){
            document.getElementsByClassName('trade_main_modal')[0].className = "trade_main_modal v-transfer-dom " +localStorage.getItem("themeValue");
          }
        }else{
          localStorage.setItem("themeValue","dark");
          document.getElementById('app').className =localStorage.getItem("themeValue");
          if(document.getElementsByClassName('trade_main_modal')[0] !== undefined){
            document.getElementsByClassName('trade_main_modal')[0].className = "trade_main_modal v-transfer-dom " +localStorage.getItem("themeValue");
          }
        }
      },
      computed: {
        access () {
          return this.$store.state.user.access
        },
        viewAccessAll () {
          return hasOneOf(['trader'], this.access)
        },
        viewAccessSuper () {
          return hasOneOf(['admin'], this.access)
        },
        computed_client(){   //vux要监听对象
          return this.get_client()
        },
        computed_contract(){
          return this.get_contract()
        },
        client_and_contract(){   //如果client和contract都发生改变执行
          const  { clientSelected,contractSelected} = this;
          return {
            clientSelected,
            contractSelected
          }
        },
      },
      watch:{
        computed_client(){
          this.clientSelected = this.get_client();
        },
        computed_contract(){
          this.contractSelected = this.get_contract()
          removeWatermark();
          this.contractSelected = this.get_contract()
          // 币安
          var patt1 = /USDT-B/i;
          var patt2 = /USD-B/i;
          // ok
          var patt3 = /USDT-O/i;
          var patt4 = /USD-O/i;
          // bitmex
          var patt5 = /XBT/i;
          // 火币
          var patt6 = /USDT/i;
          var patt7 = /USD/i;
          if(patt1.test(this.contractSelected)){
            setWaterMark('', 'USDT-binance(欧)','#f17c00');
            this.bourse = "binance"
          } else if (patt2.test(this.contractSelected)){
            setWaterMark('', 'BTC-binance(火)','#f17c00');
            this.bourse = "binance"
          }else if (patt3.test(this.contractSelected)){
            setWaterMark('', 'USDT-ok','#00f100');
            this.bourse = "okex"
          }else if (patt4.test(this.contractSelected)){
            setWaterMark('', 'BTC-ok','#00f100');
            this.bourse = "okex"
          }else if (patt5.test(this.contractSelected)){
            setWaterMark('', 'BTC-bitmex(火)','#f10034');
            this.bourse = "bitmex"
          }else if (patt6.test(this.contractSelected)){
            setWaterMark('', 'USDT-huobi','#0054f1');
            this.bourse = "huobi"
          }else if (patt7.test(this.contractSelected)){
            setWaterMark('', 'BTC-huobi','#0054f1');
            this.bourse = "huobi"
          }
        },
        client_and_contract(){ //获取到用户id和合约后执行的方法
          console.log(this.contractSelected)
          if(this.clientSelected !== '' && this.contractSelected !=='' && this.contractSelected !==undefined){
            this.get_DefultTime();
          }
        },
      }
    }
</script>

<style scoped lang="less">
  .header-bar {
    height: 80px;
    display: flex;
    margin-bottom: 10px;
    .layout-logo {
      width: 300px;
      height: 30px;
      position: relative;
      top: 23px;
      left: 29px;
    }
    .header-enu{
      position: relative;
      top: 10px;
      left: 211px;
      /deep/ .ivu-menu-item{
        font-size: 18px;
        /*color: #72757F;*/
        letter-spacing: 0;
        text-align: center;
      }
    }
    .select-time{
      position: relative;
      left: 211px;
      //flex: 2;
      text-align: right;
      margin-top:25px;
      margin-right: -170px;
      /deep/ .ivu-input{
        background-color: #161c39;
        border: 1px solid #45568d;
        color: #808695;
      }
    }
    .custom-content-con{
      position: relative;
      left: 411px;

      //flex: 1;
      text-align: right;
      margin-top:5px;
      margin-right: 60px;
      .ivu-dropdown{
        cursor: pointer;
      }
    }
  }
  .ivu-menu-dark{
    background:transparent;
  }
</style>
